import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:playtruly/common/index.dart';  // 使用公共索引文件
import 'package:playtruly/common/api/friend_api.dart';  // 导入好友API
import 'package:playtruly/common/api/user_api.dart';  // 🔥 导入用户API（用于获取用户信息）
import 'package:playtruly/common/models/index.dart';    // 导入好友列表模型
import 'package:playtruly/common/services/user_service.dart'; // 🔑 用户服务
import 'package:playtruly/common/services/rongcloud_service.dart'; // 🔥 导入融云服务
import 'package:playtruly/common/utils/toast_util.dart';
import 'package:playtruly/pages/message/message_chat/controller.dart';  // 导入ChatUser类
import 'package:playtruly/common/services/notification_manager.dart'; // 🔥 导入通知管理器
import 'dart:developer' as developer;

// 聊天模型
class ChatModel {
  final String id;
  final String name;
  final String avatarUrl;
  final String lastMessage;
  final DateTime lastMessageTime;
  final bool isUnread;
  final int unreadCount;

  ChatModel({
    required this.id,
    required this.name,
    required this.avatarUrl,
    this.lastMessage = '',
    DateTime? lastMessageTime,
    this.isUnread = false,
    this.unreadCount = 0,
  }) : lastMessageTime = lastMessageTime ?? DateTime.now();
}

class MessageIndexController extends GetxController {
  MessageIndexController();

  // 聊天列表
  final RxList<ChatModel> chatList = <ChatModel>[].obs;
  
  // 好友列表（从API获取）
  final RxList<FriendInfo> friendList = <FriendInfo>[].obs;
  
  // 加载状态
  final RxBool isLoadingFriends = false.obs;
  
  // 当前用户ID（从UserService动态获取）
  final RxInt currentUserId = 0.obs;

  // 头像URL列表
  final List<String> avatarUrls = [
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_1.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_2.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_3.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_4.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_5.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_6.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_7.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_8.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_9.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_10.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_11.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_12.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_13.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_14.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_15.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_16.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_17.webp",
    "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/user_test/user_18.webp",
  ];

  // 用户名列表
  final List<String> userNames = [
    "手刹拉过大楼",
    "翻山越岭",
    "不辜负生命",
    "落日余晖",
    "天才少女",
    "静水流深",
    "白昼星辰",
    "鸿鹄志",
    "玫瑰与星辰",
    "若有所思"
  ];

  // 好友申请列表（本地模型）
  final RxList<FriendRequest> friendRequests = <FriendRequest>[].obs;
  
  // 真实好友申请列表（从API获取）
  final RxList<FriendRequestInfo> realFriendRequests = <FriendRequestInfo>[].obs;
  
  // 好友申请加载状态
  final RxBool isLoadingFriendRequests = false.obs;
  
  // 删除好友状态
  final RxBool isDeletingFriend = false.obs;

  // 🔥 好友申请通知状态管理
  final RxBool hasFriendRequestNotification = false.obs;  // 是否有好友申请通知

  // 初始化数据
  void _initData() {
    // 🎯 加载真实好友列表数据
    _loadFriendsList().then((_) {
      // 🔍 数据加载完成后验证去重效果
      _validateNoDuplicates();
      
      // 🔥 加载完成后检查新消息缓存
      _checkAndUpdateNewMessages();
    });
    // 生成模拟好友申请数据（后续可替换为真实API）
    _generateMockFriendRequests();
    update(["message_index"]);
  }

  // 加载好友列表
  Future<void> _loadFriendsList() async {
    try {
      isLoadingFriends.value = true;
      developer.log('🔄 =============== 开始加载好友列表 ===============');
      developer.log('👤 当前用户ID: $currentUserId');
      
      // 🔥 调用好友列表API（参考MyApplication2的实现）
      final response = await FriendApi.getFriendList(
        userId: currentUserId.value,
        // groupId: null,  // 分组ID(可选)
        // status: null,   // 状态(可选)  
      );
      
      developer.log('📨 好友列表API响应: ${response.status}');
      
      if (response.isSuccess) {
        // 🎯 对API返回的数据进行去重处理（基于friendId）
        final Map<int, FriendInfo> uniqueFriendsMap = {};
        for (final friend in response.data) {
          uniqueFriendsMap[friend.friendId] = friend;
        }
        final deduplicatedFriends = uniqueFriendsMap.values.toList();
        
        developer.log('🔍 去重处理: 原始${response.data.length}个好友 → 去重后${deduplicatedFriends.length}个好友');
        if (response.data.length != deduplicatedFriends.length) {
          developer.log('⚠️ 检测到重复好友数据，已自动去重');
          // 打印重复的好友信息用于调试
          final duplicateCount = response.data.length - deduplicatedFriends.length;
          developer.log('📊 去除了 $duplicateCount 个重复好友');
        }
        
        // 🎯 将去重后的好友数据转换为聊天列表
        friendList.assignAll(deduplicatedFriends);
        _convertFriendsToChats(deduplicatedFriends);
        
        developer.log('✅ 好友列表加载成功: ${deduplicatedFriends.length}个好友');
        for (final friend in deduplicatedFriends) {
          developer.log('   👤 ${friend.username} (ID: ${friend.friendId})');
        }
      } else {
        developer.log('❌ 好友列表加载失败: ${response.message}');
        // API调用失败时，使用模拟数据
        _generateMockChatList();
      }
      
    } catch (e) {
      developer.log('💥 加载好友列表异常: $e');
      // 异常时使用模拟数据
      _generateMockChatList();
    } finally {
      isLoadingFriends.value = false;
      developer.log('🏁 =============== 好友列表加载结束 ===============');
    }
  }

  // 将好友数据转换为聊天列表
  void _convertFriendsToChats(List<FriendInfo> friends) {
    chatList.clear();
    
    // 🔍 使用Map确保聊天列表去重（基于好友ID）
    final Map<String, ChatModel> uniqueChatsMap = {};
    
    // 🔥 获取融云服务实例来检查新消息缓存
    final rongCloudService = RongCloudService.to;
    
    for (final friend in friends) {
      final friendIdStr = friend.friendId.toString();
      
      // 🔥 检查该好友是否有新消息
      final hasNewMessage = rongCloudService.hasNewMessage(friendIdStr);
      final latestMessage = rongCloudService.getLatestMessage(friendIdStr);
      final unreadCount = rongCloudService.getUnreadMessageCount(friendIdStr); // 🔥 获取真实的未读消息数量
      
      // 🔥 根据是否有新消息确定显示内容
      String lastMessage = '点击开始聊天';
      bool isUnread = false;
      
      if (hasNewMessage && latestMessage != null) {
        // 有新消息时显示最新消息内容
        lastMessage = latestMessage['content'] ?? '收到新消息';
        isUnread = true;
        developer.log('🔔 好友 ${friend.username} 有新消息: $lastMessage (数量: $unreadCount)');
      }
      
      final chatModel = ChatModel(
        id: friendIdStr,
        name: friend.username.isNotEmpty ? friend.username : '未知用户',
        avatarUrl: friend.userAvatarUrl.isNotEmpty 
            ? friend.userAvatarUrl 
            : avatarUrls[friend.friendId % avatarUrls.length], // 使用默认头像
        lastMessage: lastMessage,
        lastMessageTime: hasNewMessage && latestMessage != null
            ? DateTime.fromMillisecondsSinceEpoch(latestMessage['timestamp'])
            : DateTime.now().subtract(Duration(hours: friend.friendId % 24)),
        isUnread: isUnread, // 🔥 根据新消息状态设置未读标识
        unreadCount: unreadCount, // 🔥 使用真实的未读消息数量
      );
      
      // 检查是否为重复项
      if (uniqueChatsMap.containsKey(friendIdStr)) {
        developer.log('⚠️ 发现重复聊天项目: ${friend.username} (ID: $friendIdStr)，已忽略');
      } else {
        uniqueChatsMap[friendIdStr] = chatModel;
        developer.log('✅ 添加聊天项目: ${friend.username} (ID: $friendIdStr) ${isUnread ? "[有$unreadCount条新消息]" : ""}');
      }
    }
    
    // 🔥 将有新消息的聊天排在前面，然后添加到列表
    final chatsWithMessages = uniqueChatsMap.values.where((chat) => chat.isUnread).toList();
    final chatsWithoutMessages = uniqueChatsMap.values.where((chat) => !chat.isUnread).toList();
    
    // 先添加有新消息的聊天，再添加无新消息的聊天
    chatList.addAll(chatsWithMessages);
    chatList.addAll(chatsWithoutMessages);
    
    developer.log('🎨 好友数据转换完成: 输入${friends.length}个好友 → 输出${chatList.length}个聊天项目');
    developer.log('🔔 其中${chatsWithMessages.length}个有新消息，${chatsWithoutMessages.length}个无新消息');
    
    // 🔍 打印最终聊天列表用于调试
    developer.log('📋 最终聊天列表:');
    for (int i = 0; i < chatList.length; i++) {
      final chat = chatList[i];
      final countText = chat.isUnread && chat.unreadCount > 0 ? "[🔴${chat.unreadCount}条新消息]" : "";
      developer.log('   ${i + 1}. ${chat.name} (ID: ${chat.id}) $countText');
    }
  }

  // 生成模拟聊天数据
  void _generateMockChatList() {
    // 清空现有列表
    chatList.clear();
    
    // 添加多个聊天
    for (int i = 0; i < 5; i++) {
      chatList.add(
        ChatModel(
          id: (i + 1).toString(),
          name: userNames[i % userNames.length],
          avatarUrl: avatarUrls[i % avatarUrls.length],
        )
      );
    }
  }

  // 城市列表
  final List<String> cities = [
    "上海", "北京", "广州", "深圳", "杭州", 
    "成都", "重庆", "武汉", "西安", "南京"
  ];
  
  // 个性签名列表
  final List<String> signatures = [
    "往后每一天都是第一天",
    "生活需要仪式感",
    "做自己的太阳",
    "简单快乐就好",
    "热爱生活，拥抱未来",
    "愿你眼中总有光芒",
    "保持热爱，奔赴山海",
    "温柔且坚定",
    "岁月不败美人",
    "心有猛虎，细嗅蔷薇"
  ];

  // 生成模拟好友申请数据
  void _generateMockFriendRequests() {
    friendRequests.clear();
    
    // 添加5个好友申请
    for (int i = 0; i < 5; i++) {
      final now = DateTime.now();
      friendRequests.add(
        FriendRequest(
          id: "req_${i + 1}",
          name: userNames[(i + 5) % userNames.length],
          avatarUrl: avatarUrls[(i + 5) % avatarUrls.length],
          level: (i + 1) * 8 + 15, // 等级15-47
          gender: i % 2 == 0 ? "female" : "male",
          city: cities[i % cities.length],
          age: 20 + (i * 3), // 年龄20-32
          signature: signatures[i % signatures.length],
          requestTime: now.subtract(Duration(hours: i * 2)),
          expireTime: now.add(Duration(hours: 24 - (i * 2))), // 24小时内过期
        )
      );
    }
  }

  // 🔥 跳转到聊天详情页（修复时序问题）
  Future<void> goToChatDetail(ChatModel chat) async {
    try {
      developer.log('🎯 准备跳转到聊天页面: ${chat.name}');
      developer.log('📊 跳转前消息状态: 是否有新消息=${chat.isUnread}, 未读数量=${chat.unreadCount}');
      
      // 🔥 只清除UI中的未读状态，但保留消息内容（等聊天页面初始化后再清除）
      if (chat.isUnread) {
        markChatAsRead(chat.id);
      }
      
      // 🔥 确保融云连接（非阻塞）
      final rongCloudService = RongCloudService.to;
      if (!rongCloudService.isConnected.value) {
        developer.log('🔄 跳转前确保融云连接');
        rongCloudService.connectIM(); // 非阻塞连接
      }
      
      // 🔥 创建聊天用户对象（保持完整信息）
      final chatUser = ChatUser(
        id: chat.id,
        name: chat.name,
        avatarUrl: chat.avatarUrl,
      );
      
      developer.log('✅ 开始跳转到聊天页面: ${chatUser.name} (ID: ${chatUser.id})');
      developer.log('📝 注意：消息清除将在聊天页面初始化时进行，确保消息正确显示');
      
      // 🔥 导航到聊天页面（消息清除交给聊天页面处理）
      Get.toNamed(
        RouteNames.messageMessageChat,
        arguments: chatUser,
      );
      
    } catch (e) {
      developer.log('💥 跳转到聊天页面异常: $e');
      ToastUtil.error('跳转失败，请重试');
    }
  }

  /// 🎯 跳转到用户信息页面（模仿activity_detail_bottom_sheet的逻辑）
  Future<void> goToUserProfile(ChatModel chat) async {
    developer.log('🔗 点击头像，跳转到用户信息页面: ${chat.name}');
    
    try {
      // 🔥 获取用户ID（聊天ID就是用户ID）
      final targetUserId = int.tryParse(chat.id);
      if (targetUserId == null) {
        ToastUtil.error('无法获取用户信息');
        return;
      }
      
      developer.log('👤 开始获取用户信息，用户ID: $targetUserId');
      
      // 显示加载提示
      Get.dialog(
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
          ),
        ),
        barrierDismissible: false,
      );
      
      // 🚀 调用用户过滤内容API获取用户信息（与activity_detail_bottom_sheet保持一致）
      final userResponse = await UserApi.getUserFilteredContent(
        userId: targetUserId,
        contentType: 'activities', // 获取活动信息
      );
      
      // 关闭加载对话框
      Get.back();
      
      if (userResponse.isSuccess && userResponse.user != null) {
        final user = userResponse.user!;
        developer.log('✅ 成功获取用户信息: ${user.username}');
        
        // 🎯 将FilteredUserInfo转换为用户信息页面需要的参数（与activity_detail_bottom_sheet保持一致）
        final userInfo = {
          'userId': user.userid,
          'username': user.username,
          'avatar': user.userAvatarUrl ?? '',
          'signature': user.userSignature ?? '',
          'userLevel': user.userLevel ?? 0,
          'userFollowers': user.userFollowers ?? 0,
          'userLikes': user.userLikes ?? 0,
          'userPoints': user.userPoints ?? 0, // 🔥 积分字段支持等级显示
          'userTags': user.userTags ?? [],
          'userHobbies': user.userHobbies ?? [],
          'userFrequentPlaces': user.userFrequentPlaces ?? '未知',
          'userCity': user.userCity ?? '未知',
          'userImgUrls': user.userImgUrls ?? [],
          'activities': userResponse.activities ?? [], // List<ActivityData>
          'friendCount': userResponse.friendCount ?? 0,
        };
        
        // 🚀 跳转到用户信息页面
        Get.toNamed(
          RouteNames.myUserInfo,
          arguments: userInfo,
        );
        
        developer.log('✅ 用户信息页面跳转完成');
      } else {
        developer.log('❌ 获取用户信息失败: ${userResponse.message}');
        ToastUtil.error('获取用户信息失败: ${userResponse.message ?? "未知错误"}');
      }
      
    } catch (e) {
      // 关闭可能的加载对话框
      if (Get.isDialogOpen == true) {
        Get.back();
      }
      developer.log('💥 获取用户信息异常: $e');
      ToastUtil.error('获取用户信息失败');
    }
  }

  // 添加新联系人
  void addNewContact() {
    developer.log('🔄 =============== 点击添加好友图标 ===============', name: 'MessageIndex');
    developer.log('🔍 清除前状态: hasFriendRequestNotification=${hasFriendRequestNotification.value}', name: 'MessageIndex');
    
    // 🔥 1. 立即清除本地通知状态（避免UI延迟）
    hasFriendRequestNotification.value = false;
    developer.log('✅ 1. 本地通知状态已清除', name: 'MessageIndex');
    
    // 🔥 2. 清除融云服务中的好友申请状态
    try {
      final rongCloudService = RongCloudService.to;
      rongCloudService.clearPendingFriendRequestNotification();
      developer.log('✅ 2. 已清除融云服务中的好友申请状态', name: 'MessageIndex');
    } catch (e) {
      developer.log('💥 清除融云服务好友申请状态失败: $e', name: 'MessageIndex');
    }
    
    // 🔥 3. 清除NotificationManager的状态（统一管理）
    try {
      final notificationManager = NotificationManager.to;
      notificationManager.clearFriendRequestNotification();
      developer.log('✅ 3. 已清除NotificationManager中的好友申请状态', name: 'MessageIndex');
    } catch (e) {
      developer.log('💥 清除NotificationManager好友申请状态失败: $e', name: 'MessageIndex');
    }
    
    // 🔥 4. 强制更新UI状态（确保清除生效）
    update(["message_index"]);
    developer.log('✅ 4. UI状态更新已触发', name: 'MessageIndex');
    
    developer.log('🔍 清除后状态: hasFriendRequestNotification=${hasFriendRequestNotification.value}', name: 'MessageIndex');
    developer.log('🏁 =============== 好友申请通知状态清除完成 ===============', name: 'MessageIndex');
    
    // 🎯 每次点击都重新获取好友申请列表
    _loadFriendRequestsList();
  }

  /// 🔥 新增：测试通知功能（调试用）
  Future<void> testNotification() async {
    try {
      developer.log('🧪 手动测试通知功能');
      
      // 检查并修复通知权限
      final hasPermission = await NotificationService.to.checkAndFixPermissions();
      developer.log('📱 通知权限检查结果: $hasPermission');
      
      if (hasPermission) {
        // 显示测试通知
        await NotificationService.to.showFriendRequestNotification(
          userName: '测试用户',
        );
        ToastUtil.success('测试通知已发送，请检查通知栏');
      } else {
        ToastUtil.error('通知权限未授予，请在设置中开启通知权限');
      }
      
    } catch (e) {
      developer.log('💥 测试通知异常: $e');
      ToastUtil.error('测试通知失败: $e');
    }
  }



  // 刷新好友列表
  Future<void> refreshFriendsList() async {
    try {
      developer.log('🔄 用户主动刷新好友列表');
      await _loadFriendsList();
      // 🔍 刷新完成后验证去重效果
      _validateNoDuplicates();
      developer.log('✅ 好友列表刷新完成');
    } catch (e) {
      developer.log('💥 好友列表刷新失败: $e');
      // 不显示错误提示，保持静默刷新
    }
  }

  // 手动下拉刷新（带提示）
  Future<void> pullToRefresh() async {
    try {
      developer.log('📱 用户下拉刷新好友列表');
      
      // 添加短暂延迟，让用户感知到刷新动作
      await Future.delayed(const Duration(milliseconds: 300));
      
      await _loadFriendsList();
      // 🔍 下拉刷新完成后验证去重效果
      _validateNoDuplicates();
      developer.log('✅ 下拉刷新完成');
      
      // 成功后添加轻微震动反馈
      HapticFeedback.lightImpact();
      
    } catch (e) {
      developer.log('💥 下拉刷新失败: $e');
      // 下拉刷新失败时显示错误提示
      ToastUtil.error('刷新失败 - 请检查网络连接后重试');
    }
  }

  // 加载好友申请列表
  Future<void> _loadFriendRequestsList() async {
    try {
      isLoadingFriendRequests.value = true;
      developer.log('🔄 =============== 开始加载好友申请列表 ===============');
      developer.log('👤 当前用户ID: $currentUserId');
      
      // 🔥 调用好友申请列表API（参考MyApplication2的实现）
      final response = await FriendApi.getFriendRequestList(
        userId: currentUserId.value,
      );
      
      developer.log('📨 好友申请列表API响应: ${response.status}');
      
      if (response.isSuccess) {
        // 🎯 过滤好友申请列表
        final filteredRequests = response.data.where((request) {
          // 1. 排除自己给自己发的申请
          bool isNotSelfRequest = request.senderId != currentUserId.value;
          
          // 2. 只显示发给自己的申请（不管是自己发的还是别人发的，只要接收者是自己）
          bool isReceivedRequest = request.receiverId == currentUserId.value;
          
          // 3. 显示待处理和已同意的申请（pending + accepted状态）
          bool isValidStatus = request.status == 'pending' || request.status == 'accepted';
          
          // 🔍 添加调试日志
          developer.log('   🔍 申请${request.requestId}: 发送者${request.senderId} -> 接收者${request.receiverId}, 状态映射: ${request.status}, 不是自己发的:$isNotSelfRequest, 是发给自己的:$isReceivedRequest, 状态有效:$isValidStatus');
          
          return isNotSelfRequest && isReceivedRequest && isValidStatus;
        }).toList();
        
        realFriendRequests.assignAll(filteredRequests);
        
        developer.log('✅ 好友申请列表加载成功: 原始${response.count}个申请 → 过滤后${filteredRequests.length}个可显示申请（待处理+已同意）');
        
        // 打印过滤详情
        for (final request in response.data) {
          final isNotSelfRequest = request.senderId != currentUserId.value;
          final isReceivedRequest = request.receiverId == currentUserId.value;
          final isValidStatus = request.status == 'pending' || request.status == 'accepted';
          final willShow = isNotSelfRequest && isReceivedRequest && isValidStatus;
          developer.log('   📋 用户${request.senderId}(${request.senderUsername}) - 状态: ${request.status} ${!isNotSelfRequest ? "[自己发的]" : ""} ${!isReceivedRequest ? "[不是发给自己]" : ""} ${!isValidStatus ? "[已拒绝/无效]" : ""} ${willShow ? "[显示]" : "[过滤]"}');
        }
        
        if (filteredRequests.isNotEmpty) {
          developer.log('📝 可显示的好友申请:');
          for (final request in filteredRequests) {
            developer.log('   ✅ 来自用户${request.senderId}(${request.senderUsername}) - 状态: ${request.status}');
          }
        } else {
          developer.log('📭 暂无可显示的好友申请');
        }
        
        // 显示好友申请弹出框
        _showFriendRequestsBottomSheet();
      } else {
        developer.log('❌ 好友申请列表加载失败: ${response.message}');
        // API调用失败时，显示空的弹出框
        realFriendRequests.clear();
        _showFriendRequestsBottomSheet();
      }
      
    } catch (e) {
      developer.log('💥 加载好友申请列表异常: $e');
      // 异常时显示空的弹出框
      realFriendRequests.clear();
      _showFriendRequestsBottomSheet();
    } finally {
      isLoadingFriendRequests.value = false;
      developer.log('🏁 =============== 好友申请列表加载结束 ===============');
    }
  }
  
  // 显示底部弹出的好友申请列表
  void _showFriendRequestsBottomSheet() {
    Get.bottomSheet(
      Container(
        height: Get.height * 0.8,
        padding: const EdgeInsets.symmetric(vertical: 20),
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          children: [
            // 标题
            const Padding(
              padding: EdgeInsets.only(bottom: 16),
              child: Text(
                "好友申请",
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            // 列表
            Expanded(
              child: Obx(() {
                // 🔄 显示加载状态
                if (isLoadingFriendRequests.value) {
                  return const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(),
                        SizedBox(height: 16),
                        Text('正在加载好友申请...'),
                      ],
                    ),
                  );
                }
                
                // 📭 空状态
                if (realFriendRequests.isEmpty) {
                  return const Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.person_add_disabled,
                          size: 64,
                          color: Colors.grey,
                        ),
                        SizedBox(height: 16),
                        Text(
                          '暂无好友申请',
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                  );
                }
                
                // 📝 好友申请列表
                return ListView.builder(
                  itemCount: realFriendRequests.length,
                  itemBuilder: (context, index) {
                    final request = realFriendRequests[index];
                    return _buildRealFriendRequestItem(request);
                  },
                );
              }),
            ),
          ],
        ),
      ),
      backgroundColor: Colors.transparent,
      elevation: 0,
      isScrollControlled: true,
    );
  }
  

  

  
  // 构建真实好友申请列表项
  Widget _buildRealFriendRequestItem(FriendRequestInfo request) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        children: [
          // 头像
          ClipRRect(
            borderRadius: BorderRadius.circular(25),
            child: Image.network(
              request.senderAvatar ?? avatarUrls[request.senderId % avatarUrls.length],
              width: 50,
              height: 50,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  width: 50,
                  height: 50,
                  color: Colors.grey[300],
                  child: const Icon(Icons.person, color: Colors.grey, size: 25),
                );
              },
            ),
          ),
          const SizedBox(width: 12),
          // 基本信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 昵称
                Text(
                  request.senderUsername ?? '未知用户',
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                // 申请消息
                if (request.message != null && request.message!.isNotEmpty)
                  Text(
                    request.message!,
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[700],
                      fontStyle: FontStyle.italic,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                // 申请时间
                Text(
                  _formatRequestTime(request.createdAt),
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(width: 8),
          // 同意按钮
          _buildRealActionButton(request),
        ],
      ),
    );
  }

  // 构建真实操作按钮
  Widget _buildRealActionButton(FriendRequestInfo request) {
    // 根据申请状态显示不同按钮
    if (request.status == 'accepted') {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.grey[300],
          borderRadius: BorderRadius.circular(15),
        ),
        child: const Text(
          "已通过",
          style: TextStyle(
            color: Colors.grey,
            fontSize: 11,
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    } else if (request.status == 'rejected') {
      return Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.red[100],
          borderRadius: BorderRadius.circular(15),
        ),
        child: const Text(
          "已拒绝",
          style: TextStyle(
            color: Colors.red,
            fontSize: 11,
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    } else {
      // pending状态，显示同意按钮
      return GestureDetector(
        onTap: () => _acceptRealFriendRequest(request),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
          decoration: BoxDecoration(
            color: const Color(0xFFE33641),
            borderRadius: BorderRadius.circular(15),
          ),
          child: const Text(
            "同意",
            style: TextStyle(
              color: Colors.white,
              fontSize: 11,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      );
    }
  }

  // 处理真实好友申请
  Future<void> _acceptRealFriendRequest(FriendRequestInfo request) async {
    try {
      developer.log('🔄 =============== 开始处理好友申请 ===============');
      developer.log('📝 申请ID: ${request.requestId}');
      developer.log('👤 发送者: ${request.senderUsername}');
      
      // 🔥 调用处理好友申请API（参考MyApplication2的实现）
      final response = await FriendApi.handleFriendRequest(
        requestId: request.requestId,
        action: 'accept', // 同意操作
      );
      
      developer.log('📨 处理好友申请API响应: ${response.status}');
      
      if (response.isSuccess) {
        developer.log('✅ 好友申请处理成功');
        developer.log('🤝 好友关系ID: ${response.friendshipId}');
        
        // 🎯 处理成功后的操作
        // 1. 更新本地申请状态
        final index = realFriendRequests.indexWhere((r) => r.requestId == request.requestId);
        if (index != -1) {
          // 由于FriendRequestInfo没有可变的status字段，我们需要创建新对象或移除这个申请
          realFriendRequests.removeAt(index);
        }
        
        // 2. 刷新好友列表
        await _loadFriendsList();
        
        // 3. 显示成功提示
        ToastUtil.success('已添加 ${request.senderUsername ?? "该用户"} 为好友');
        
      } else {
        developer.log('❌ 好友申请处理失败: ${response.message}');
        ToastUtil.error('失败 - ${response.message}');
      }
      
    } catch (e) {
      developer.log('💥 处理好友申请异常: $e');
      ToastUtil.error('错误 - 处理好友申请失败，请重试');
    }
  }

  // 格式化申请时间
  String _formatRequestTime(String createdAt) {
    try {
      final time = DateTime.parse(createdAt);
      final now = DateTime.now();
      final difference = now.difference(time);
      
      if (difference.inDays > 0) {
        return '${difference.inDays}天前';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return '未知时间';
    }
  }




  @override
  void onReady() {
    super.onReady();
    developer.log('📱 MessageIndexController - onReady() 页面准备就绪');
    _initData();
    
    // 🔥 检查是否需要自动打开好友申请弹出框（来自通知点击）
    _checkAutoShowFriendRequests();
  }

  @override
  void onInit() {
    super.onInit();
    developer.log('🔧 MessageIndexController - onInit() 控制器初始化');
    
    // 🔑 初始化用户ID
    _initializeUserId();
    
    // 🔥 注册通知回调到NotificationManager（延迟注册，确保NotificationManager已初始化）
    Future.delayed(const Duration(milliseconds: 100), () {
      try {
        final notificationManager = NotificationManager.to;
        notificationManager.registerNotificationCallback((hasNotification) {
          hasFriendRequestNotification.value = hasNotification;
          developer.log('🔔 MessageIndex收到NotificationManager通知更新: $hasNotification', name: 'MessageIndex');
        });
        developer.log('✅ MessageIndex已注册通知回调', name: 'MessageIndex');
      } catch (e) {
        developer.log('💥 MessageIndex注册通知回调失败: $e', name: 'MessageIndex');
        developer.log('🔄 尝试降级方案：直接监听hasFriendRequestNotification', name: 'MessageIndex');
        // 降级方案：如果NotificationManager不可用，保持原有功能
      }
      
      // 🔥 智能检查融云服务中是否有待处理的好友申请（避免重复显示）
      try {
        final rongCloudService = RongCloudService.to;
        final notificationManager = NotificationManager.to;
        
        // 🔥 优先检查NotificationManager的状态（统一管理）
        if (notificationManager.hasFriendRequestNotificationStatus) {
          hasFriendRequestNotification.value = true;
          developer.log('🔔 从NotificationManager检测到待处理的好友申请，已设置通知状态', name: 'MessageIndex');
        } else if (rongCloudService.hasPendingFriendRequestNotification()) {
          // 🔥 只有当NotificationManager没有状态时，才检查融云服务状态
          developer.log('⚠️ 发现NotificationManager和融云服务状态不一致，进行同步', name: 'MessageIndex');
          hasFriendRequestNotification.value = true;
          // 🔥 同步状态到NotificationManager
          notificationManager.setFriendRequestNotification(true);
          developer.log('✅ 状态已同步到NotificationManager', name: 'MessageIndex');
        } else {
          // 🔥 确保状态一致为false
          hasFriendRequestNotification.value = false;
          developer.log('✅ 确认没有待处理的好友申请，状态保持清除', name: 'MessageIndex');
        }
      } catch (e) {
        developer.log('💥 检查好友申请状态失败: $e', name: 'MessageIndex');
        // 异常情况下保持安全状态
        hasFriendRequestNotification.value = false;
      }
    });
  }
  
  /// 🔑 初始化用户ID
  void _initializeUserId() {
    try {
      final userService = UserService.to;
      if (userService.isLoggedIn && userService.currentUser != null) {
        currentUserId.value = userService.currentUser!.userid;
        developer.log('✅ MessageIndex - 从UserService获取用户ID: ${currentUserId.value} (${userService.currentUser!.username})');
      } else {
        currentUserId.value = 0;
        developer.log('⚠️ MessageIndex - 用户未登录，设置用户ID为: 0');
      }
      
      // 🔄 监听用户信息变化（简化逻辑，暂时移除监听器）
      // TODO: 如果需要实时响应用户登录状态变化，可以在合适的时候重新调用_initializeUserId()
    } catch (e) {
      developer.log('💥 MessageIndex - 初始化用户ID失败: $e');
      currentUserId.value = 0;
    }
  }

  /// 🔥 检查是否需要自动打开好友申请弹出框（来自通知点击）
  void _checkAutoShowFriendRequests() {
    try {
      // 获取页面传入的参数
      final arguments = Get.arguments;
      if (arguments is Map && arguments['auto_show_friend_requests'] == true) {
        developer.log('🤝 检测到通知点击，准备自动打开好友申请弹出框');
        
        // 延迟一小段时间确保页面完全加载，然后自动打开好友申请弹出框
        Future.delayed(const Duration(milliseconds: 800), () {
          developer.log('🚀 自动触发好友申请弹出框');
          addNewContact(); // 复用现有的addNewContact方法
        });
      }
    } catch (e) {
      developer.log('💥 检查自动打开好友申请弹出框失败: $e');
    }
  }

  /// 🔥 新增：标记特定聊天为未读（收到新消息时调用）
  void markChatAsUnread(String senderId, {int messageCount = 1}) {
    try {
      developer.log('🔔 =============== 标记聊天为未读 ===============');
      developer.log('📨 发送者ID: $senderId');
      developer.log('📊 消息数量: $messageCount');
      
      // 查找对应的聊天项
      final chatIndex = chatList.indexWhere((chat) => chat.id == senderId);
      
      if (chatIndex != -1) {
        final currentChat = chatList[chatIndex];
        developer.log('✅ 找到聊天项: ${currentChat.name} (ID: ${currentChat.id})');
        
        // 创建新的ChatModel实例以更新未读状态
        final updatedChat = ChatModel(
          id: currentChat.id,
          name: currentChat.name,
          avatarUrl: currentChat.avatarUrl,
          lastMessage: '收到新消息', // 可以后续从具体消息内容获取
          lastMessageTime: DateTime.now(),
          isUnread: true,
          unreadCount: currentChat.unreadCount + messageCount,
        );
        
        // 替换聊天项
        chatList[chatIndex] = updatedChat;
        
        developer.log('🔔 聊天标记为未读成功:');
        developer.log('   用户: ${updatedChat.name}');
        developer.log('   未读数量: ${updatedChat.unreadCount}');
        developer.log('   最后消息时间: ${updatedChat.lastMessageTime}');
        
        // 🎯 将有新消息的聊天移到列表顶部
        if (chatIndex > 0) {
          chatList.removeAt(chatIndex);
          chatList.insert(0, updatedChat);
          developer.log('📌 聊天已移至列表顶部');
        }
        
        // 手动触发UI更新
        update(["message_index"]);
        developer.log('🔄 UI更新已触发');
        
      } else {
        developer.log('⚠️ 未找到ID为 $senderId 的聊天项');
        // 打印当前聊天列表用于调试
        developer.log('🔍 当前聊天列表:');
        for (int i = 0; i < chatList.length; i++) {
          developer.log('   [$i] ID=${chatList[i].id}, Name=${chatList[i].name}');
        }
        
        // 🎯 如果未找到聊天项，可能是新联系人，尝试刷新好友列表
        developer.log('🔄 尝试刷新好友列表以获取新联系人...');
        refreshFriendsList();
      }
      
    } catch (e) {
      developer.log('💥 标记聊天为未读失败: $e');
    }
  }

  /// 🔥 新增：清除特定聊天的未读状态（进入聊天页面时调用）
  void markChatAsRead(String chatId) {
    try {
      developer.log('👀 =============== 标记聊天为已读 ===============');
      developer.log('📨 聊天ID: $chatId');
      
      // 查找对应的聊天项
      final chatIndex = chatList.indexWhere((chat) => chat.id == chatId);
      
      if (chatIndex != -1) {
        final currentChat = chatList[chatIndex];
        developer.log('✅ 找到聊天项: ${currentChat.name} (ID: ${currentChat.id})');
        
        // 如果当前就是未读状态，才需要更新
        if (currentChat.isUnread) {
          // 创建新的ChatModel实例以清除未读状态
          final updatedChat = ChatModel(
            id: currentChat.id,
            name: currentChat.name,
            avatarUrl: currentChat.avatarUrl,
            lastMessage: currentChat.lastMessage,
            lastMessageTime: currentChat.lastMessageTime,
            isUnread: false,
            unreadCount: 0,
          );
          
          // 替换聊天项
          chatList[chatIndex] = updatedChat;
          
          developer.log('👀 聊天标记为已读成功: ${updatedChat.name}');
          
          // 手动触发UI更新
          update(["message_index"]);
          developer.log('🔄 UI更新已触发');
        } else {
          developer.log('ℹ️ 聊天已经是已读状态，无需更新');
        }
        
      } else {
        developer.log('⚠️ 未找到ID为 $chatId 的聊天项');
      }
      
    } catch (e) {
      developer.log('💥 标记聊天为已读失败: $e');
    }
  }

  /// 🔥 新增：获取总未读消息数量（用于底部导航栏红点）
  int getTotalUnreadCount() {
    try {
      int totalCount = 0;
      for (final chat in chatList) {
        if (chat.isUnread) {
          totalCount += chat.unreadCount;
        }
      }
      developer.log('📊 总未读消息数量: $totalCount');
      return totalCount;
    } catch (e) {
      developer.log('💥 获取总未读消息数量失败: $e');
      return 0;
    }
  }

  /// 🔥 新增：更新聊天的最后消息内容
  void updateChatLastMessage(String senderId, String message, {String? senderName}) {
    try {
      developer.log('💬 =============== 更新聊天最后消息 ===============');
      developer.log('📨 发送者ID: $senderId');
      developer.log('💬 消息内容: $message');
      developer.log('👤 发送者姓名: $senderName');
      
      // 查找对应的聊天项
      final chatIndex = chatList.indexWhere((chat) => chat.id == senderId);
      
      if (chatIndex != -1) {
        final currentChat = chatList[chatIndex];
        developer.log('✅ 找到聊天项: ${currentChat.name} (ID: ${currentChat.id})');
        
        // 创建新的ChatModel实例以更新最后消息
        final updatedChat = ChatModel(
          id: currentChat.id,
          name: senderName ?? currentChat.name, // 如果提供了发送者姓名，更新姓名
          avatarUrl: currentChat.avatarUrl,
          lastMessage: message.length > 30 ? '${message.substring(0, 30)}...' : message, // 限制显示长度
          lastMessageTime: DateTime.now(),
          isUnread: true, // 收到新消息标记为未读
          unreadCount: currentChat.unreadCount + 1,
        );
        
        // 替换聊天项
        chatList[chatIndex] = updatedChat;
        
        // 🎯 将有新消息的聊天移到列表顶部
        if (chatIndex > 0) {
          chatList.removeAt(chatIndex);
          chatList.insert(0, updatedChat);
          developer.log('📌 聊天已移至列表顶部');
        }
        
        developer.log('💬 聊天最后消息更新成功:');
        developer.log('   用户: ${updatedChat.name}');
        developer.log('   最后消息: ${updatedChat.lastMessage}');
        developer.log('   未读数量: ${updatedChat.unreadCount}');
        
        // 手动触发UI更新
        update(["message_index"]);
        developer.log('🔄 UI更新已触发');
        
      } else {
        developer.log('⚠️ 未找到ID为 $senderId 的聊天项，尝试创建新聊天项');
        
        // 🎯 如果找不到聊天项，可能是新联系人，尝试添加到列表
        _createNewChatFromMessage(senderId, message, senderName);
      }
      
    } catch (e) {
      developer.log('💥 更新聊天最后消息失败: $e');
    }
  }

  /// 🔥 新增：从新消息创建聊天项（当收到未知联系人消息时）
  void _createNewChatFromMessage(String senderId, String message, String? senderName) {
    try {
      developer.log('🆕 =============== 创建新聊天项 ===============');
      developer.log('📨 发送者ID: $senderId');
      developer.log('👤 发送者姓名: $senderName');
      
      // 创建新的聊天项
      final newChat = ChatModel(
        id: senderId,
        name: senderName ?? '新联系人',
        avatarUrl: avatarUrls[int.parse(senderId) % avatarUrls.length], // 使用默认头像
        lastMessage: message.length > 30 ? '${message.substring(0, 30)}...' : message,
        lastMessageTime: DateTime.now(),
        isUnread: true,
        unreadCount: 1,
      );
      
      // 添加到聊天列表顶部
      chatList.insert(0, newChat);
      
      developer.log('🆕 新聊天项创建成功:');
      developer.log('   用户: ${newChat.name}');
      developer.log('   ID: ${newChat.id}');
      developer.log('   最后消息: ${newChat.lastMessage}');
      
      // 手动触发UI更新
      update(["message_index"]);
      developer.log('🔄 UI更新已触发');
      
    } catch (e) {
      developer.log('💥 创建新聊天项失败: $e');
    }
  }

  /// 🔥 新增：静态方法 - 供外部调用更新聊天未读状态（融云消息处理系统使用）
  static void updateChatUnreadFromExternal({
    required String senderId,
    required String message,
    String? senderName,
  }) {
    try {
      developer.log('🌐 =============== 外部调用更新聊天状态 ===============');
      developer.log('📨 发送者ID: $senderId');
      developer.log('💬 消息内容: $message');
      developer.log('👤 发送者姓名: $senderName');
      
      // 尝试获取MessageIndexController实例
      if (Get.isRegistered<MessageIndexController>()) {
        final controller = Get.find<MessageIndexController>();
        developer.log('✅ 找到MessageIndexController实例，更新聊天状态');
        
        // 调用实例方法更新聊天状态
        controller.updateChatLastMessage(senderId, message, senderName: senderName);
        
        developer.log('🔔 聊天状态更新完成');
      } else {
        developer.log('⚠️ MessageIndexController未注册，无法更新聊天状态');
        developer.log('💡 这可能是因为用户还没有打开聊天页面');
      }
      
    } catch (e) {
      developer.log('💥 外部更新聊天状态失败: $e');
    }
  }

  /// 🔥 新增：静态方法 - 获取聊天列表控制器实例（如果存在）
  static MessageIndexController? getInstance() {
    try {
      if (Get.isRegistered<MessageIndexController>()) {
        return Get.find<MessageIndexController>();
      }
      return null;
    } catch (e) {
      developer.log('💥 获取MessageIndexController实例失败: $e');
      return null;
    }
  }

  // 🔥 设置好友申请通知状态（供外部调用）
  void setFriendRequestNotification(bool hasNotification) {
    hasFriendRequestNotification.value = hasNotification;
    developer.log('🔔 好友申请通知状态更新: $hasNotification', name: 'MessageIndex');
  }

  // 🔥 清除好友申请通知状态（点击好友申请图标时调用）
  void clearFriendRequestNotification() {
    developer.log('🗑️ =============== 清除好友申请通知状态 ===============', name: 'MessageIndex');
    developer.log('🔍 清除前状态: hasFriendRequestNotification=${hasFriendRequestNotification.value}', name: 'MessageIndex');
    
    // 🔥 1. 立即清除本地状态
    hasFriendRequestNotification.value = false;
    developer.log('✅ 1. 本地通知状态已清除', name: 'MessageIndex');
    
    // 🔥 2. 清除NotificationManager中的状态（统一管理优先）
    try {
      final notificationManager = NotificationManager.to;
      notificationManager.clearFriendRequestNotification();
      developer.log('✅ 2. NotificationManager状态已清除', name: 'MessageIndex');
    } catch (e) {
      developer.log('💥 清除NotificationManager状态失败: $e', name: 'MessageIndex');
    }
    
    // 🔥 3. 清除融云服务中的好友申请状态
    try {
      final rongCloudService = RongCloudService.to;
      rongCloudService.clearPendingFriendRequestNotification();
      developer.log('✅ 3. 融云服务状态已清除', name: 'MessageIndex');
    } catch (e) {
      developer.log('💥 清除融云服务状态失败: $e', name: 'MessageIndex');
    }
    
    // 🔥 4. 强制更新UI（确保清除立即生效）
    update(["message_index"]);
    developer.log('✅ 4. UI更新已触发', name: 'MessageIndex');
    
    developer.log('🔍 清除后状态: hasFriendRequestNotification=${hasFriendRequestNotification.value}', name: 'MessageIndex');
    developer.log('🏁 =============== 好友申请通知状态清除完成 ===============', name: 'MessageIndex');
  }

  // 🔥 获取好友申请通知状态
  bool get friendRequestNotificationStatus => hasFriendRequestNotification.value;

  /// 🔥 新增：页面可见性变化处理（从后台返回前台时）
  void onPageVisible() {
    try {
      developer.log('👀 MessageIndex页面变为可见，刷新数据');
      
      // 页面变为可见时，刷新好友列表和未读状态
      refreshFriendsList();
      
      // 🔍 验证当前未读状态
      int totalUnread = getTotalUnreadCount();
      developer.log('📊 当前总未读消息数: $totalUnread');
      
    } catch (e) {
      developer.log('💥 页面可见性处理失败: $e');
    }
  }

  @override
  void onClose() {
    // 🔥 取消注册通知回调
    try {
      final notificationManager = NotificationManager.to;
      notificationManager.unregisterNotificationCallback((hasNotification) {
        hasFriendRequestNotification.value = hasNotification;
      });
      developer.log('✅ MessageIndex已取消注册通知回调', name: 'MessageIndex');
    } catch (e) {
      developer.log('💥 MessageIndex取消注册通知回调失败: $e', name: 'MessageIndex');
    }
    
    developer.log('💾 MessageIndexController - onClose() 控制器关闭');
    super.onClose();
  }

  // 页面重新显示时的刷新逻辑
  void onPageResumed() {
    developer.log('🔄 MessageIndexController 页面恢复 - 自动刷新好友列表');
    // 页面重新显示时自动刷新好友列表（类似MyApplication2的onResume逻辑）
    refreshFriendsList();
  }

  /// 🔥 新增：手动刷新并检查新消息缓存
  Future<void> refreshWithMessageCheck() async {
    try {
      developer.log('🔄 =============== 手动刷新并检查新消息 ===============');
      
      // 先刷新好友列表
      await _loadFriendsList();
      
      // 检查融云新消息缓存并更新UI
      _checkAndUpdateNewMessages();
      
      developer.log('✅ 刷新并检查新消息完成');
      
    } catch (e) {
      developer.log('💥 刷新并检查新消息失败: $e');
    }
  }

  /// 🔥 新增：检查并更新新消息状态
  void _checkAndUpdateNewMessages() {
    try {
      developer.log('🔍 =============== 检查新消息缓存 ===============');
      
      final rongCloudService = RongCloudService.to;
      final newMessageUserIds = rongCloudService.getAllNewMessageUserIds();
      
      developer.log('📋 当前有新消息的用户: $newMessageUserIds');
      
      if (newMessageUserIds.isEmpty) {
        developer.log('📭 没有新消息，无需更新');
        return;
      }
      
      // 更新聊天列表中对应用户的状态
      bool hasUpdates = false;
      for (int i = 0; i < chatList.length; i++) {
        final chat = chatList[i];
        final hasNewMessage = newMessageUserIds.contains(chat.id);
        
        if (hasNewMessage && !chat.isUnread) {
          // 有新消息但当前未标记为未读，需要更新
          final latestMessage = rongCloudService.getLatestMessage(chat.id);
          final unreadCount = rongCloudService.getUnreadMessageCount(chat.id); // 🔥 获取真实未读数量
          
          final updatedChat = ChatModel(
            id: chat.id,
            name: chat.name,
            avatarUrl: chat.avatarUrl,
            lastMessage: latestMessage?['content'] ?? '收到新消息',
            lastMessageTime: latestMessage != null
                ? DateTime.fromMillisecondsSinceEpoch(latestMessage['timestamp'])
                : DateTime.now(),
            isUnread: true,
            unreadCount: unreadCount, // 🔥 使用真实的未读数量
          );
          
          chatList[i] = updatedChat;
          hasUpdates = true;
          
          developer.log('🔔 更新聊天项新消息状态: ${chat.name} -> 有${unreadCount}条新消息');
        }
      }
      
      if (hasUpdates) {
        // 重新排序：有新消息的排在前面
        final chatsWithMessages = chatList.where((chat) => chat.isUnread).toList();
        final chatsWithoutMessages = chatList.where((chat) => !chat.isUnread).toList();
        
        chatList.clear();
        chatList.addAll(chatsWithMessages);
        chatList.addAll(chatsWithoutMessages);
        
        // 触发UI更新
        update(["message_index"]);
        developer.log('🔄 聊天列表已重新排序并更新UI');
      }
      
    } catch (e) {
      developer.log('💥 检查新消息缓存异常: $e');
    }
  }

  /// 🔥 新增：实时更新聊天项（供融云服务调用）
  void updateChatItemRealTime({
    required String userId,
    required int unreadCount,
    required String lastMessage,
    required String senderName,
  }) {
    try {
      developer.log('⚡ =============== 实时更新聊天项 ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('🔢 未读数量: $unreadCount');
      developer.log('💬 最新消息: $lastMessage');
      developer.log('👤 发送者: $senderName');
      
      // 查找对应的聊天项
      int chatIndex = -1;
      for (int i = 0; i < chatList.length; i++) {
        if (chatList[i].id == userId) {
          chatIndex = i;
          break;
        }
      }
      
      if (chatIndex == -1) {
        developer.log('⚠️ 未找到用户 $userId 的聊天项，无法实时更新');
        return;
      }
      
      final originalChat = chatList[chatIndex];
      
      // 创建更新后的聊天项
      final updatedChat = ChatModel(
        id: originalChat.id,
        name: originalChat.name,
        avatarUrl: originalChat.avatarUrl,
        lastMessage: lastMessage,
        lastMessageTime: DateTime.now(),
        isUnread: true,
        unreadCount: unreadCount,
      );
      
      // 更新聊天项
      chatList[chatIndex] = updatedChat;
      
      // 🔥 如果该聊天项不在第一位，需要移动到顶部
      if (chatIndex != 0) {
        chatList.removeAt(chatIndex);
        chatList.insert(0, updatedChat);
        developer.log('📈 聊天项已移动到列表顶部');
      }
      
      // 触发UI更新
      update(["message_index"]);
      
      developer.log('✅ 聊天项实时更新完成: ${originalChat.name} -> ${unreadCount}条未读消息');
      developer.log('📋 当前聊天列表第一项: ${chatList.isNotEmpty ? chatList.first.name : "空"}');
      
    } catch (e) {
      developer.log('💥 实时更新聊天项异常: $e');
    }
  }

  // 立即移除被删除的好友（供外部调用）
  void removeFriendById(String friendId) {
    try {
      developer.log('🗑️ =============== 外部调用移除好友 ===============');
      developer.log('👤 要移除的好友ID: $friendId');
      
      // 🔍 从chatList中移除被删除的好友（支持去重后的数据结构）
      final chatIndex = chatList.indexWhere((chat) => chat.id == friendId);
      if (chatIndex != -1) {
        final removedChat = chatList.removeAt(chatIndex);
        developer.log('✅ 从chatList中移除好友: ${removedChat.name} (ID: ${removedChat.id})');
      } else {
        developer.log('⚠️ 在chatList中未找到ID为 $friendId 的好友');
        // 打印当前chatList用于调试
        developer.log('🔍 当前chatList内容:');
        for (int i = 0; i < chatList.length; i++) {
          developer.log('   [$i] ID=${chatList[i].id}, Name=${chatList[i].name}');
        }
      }
      
      // 🔍 从friendList中移除被删除的好友（支持去重后的数据结构）
      final friendIndex = friendList.indexWhere((friend) => friend.friendId.toString() == friendId);
      if (friendIndex != -1) {
        final removedFriend = friendList.removeAt(friendIndex);
        developer.log('✅ 从friendList中移除好友: ${removedFriend.username} (ID: ${removedFriend.friendId})');
      } else {
        developer.log('⚠️ 在friendList中未找到ID为 $friendId 的好友');
        // 打印当前friendList用于调试
        developer.log('🔍 当前friendList内容:');
        for (int i = 0; i < friendList.length; i++) {
          developer.log('   [$i] ID=${friendList[i].friendId}, Name=${friendList[i].username}');
        }
      }
      
      developer.log('🎯 移除后chatList数量: ${chatList.length}');
      developer.log('🎯 移除后friendList数量: ${friendList.length}');
      
      // 🔍 确保移除后没有重复项（二次验证）
      _validateNoDuplicates();
      
      // 手动触发UI更新
      update(["message_index"]);
      developer.log('✅ 好友移除操作完成并触发UI更新');
      
    } catch (e) {
      developer.log('💥 移除好友失败: $e');
    }
  }

  // 🔍 验证列表中没有重复项（调试用）
  void _validateNoDuplicates() {
    try {
      // 验证chatList没有重复
      final chatIds = chatList.map((chat) => chat.id).toList();
      final uniqueChatIds = chatIds.toSet();
      if (chatIds.length != uniqueChatIds.length) {
        developer.log('⚠️ chatList中仍存在重复项！');
        final duplicates = <String>[];
        final seen = <String>{};
        for (final id in chatIds) {
          if (seen.contains(id)) {
            duplicates.add(id);
          } else {
            seen.add(id);
          }
        }
        developer.log('📊 重复的chatList ID: $duplicates');
      } else {
        developer.log('✅ chatList验证通过，无重复项');
      }
      
      // 验证friendList没有重复
      final friendIds = friendList.map((friend) => friend.friendId).toList();
      final uniqueFriendIds = friendIds.toSet();
      if (friendIds.length != uniqueFriendIds.length) {
        developer.log('⚠️ friendList中仍存在重复项！');
        final duplicates = <int>[];
        final seen = <int>{};
        for (final id in friendIds) {
          if (seen.contains(id)) {
            duplicates.add(id);
          } else {
            seen.add(id);
          }
        }
        developer.log('📊 重复的friendList ID: $duplicates');
      } else {
        developer.log('✅ friendList验证通过，无重复项');
      }
    } catch (e) {
      developer.log('💥 验证重复项失败: $e');
    }
  }

  // 显示删除好友确认对话框
  Future<bool> showDeleteConfirmDialog(ChatModel chat) async {
    return await Get.dialog<bool>(
      AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        title: Row(
          children: [
            Icon(
              Icons.warning_amber_outlined,
              color: Colors.orange,
              size: 24,
            ),
            const SizedBox(width: 12),
            const Text(
              '确认删除',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '确定要删除好友"${chat.name}"吗？',
              style: const TextStyle(
                fontSize: 16,
                color: Colors.black87,
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '删除后将无法再收发消息，所有聊天记录也将被清空。',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text(
              '取消',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 16,
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () => Get.back(result: true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            child: const Text(
              '确认删除',
              style: TextStyle(fontSize: 16),
            ),
          ),
        ],
      ),
      barrierDismissible: false,
    ) ?? false;
  }

  // 删除好友
  Future<void> deleteFriend(String friendId, String friendName) async {
    try {
      developer.log('🔄 =============== 开始删除好友 ===============');
      developer.log('👤 当前用户ID: ${currentUserId.value}');
      developer.log('👤 好友ID: $friendId');
      developer.log('👤 好友名称: $friendName');
      
      isDeletingFriend.value = true;
      
      // 调用删除好友API
      final response = await FriendApi.deleteFriend(
        userId: currentUserId.value,
        friendId: int.parse(friendId),
      );
      
      developer.log('📨 删除好友API响应: ${response.status}');
      
      if (response.isSuccess) {
        developer.log('✅ 好友删除成功: ${response.message}');
        
        // 立即从列表中移除被删除的好友（UI立即响应）
        removeFriendById(friendId);
        
        // 显示成功提示
        ToastUtil.success('已删除好友"$friendName"');
        
        developer.log('✅ 好友删除操作完成');
        
      } else {
        developer.log('❌ 好友删除失败: ${response.message}');
        ToastUtil.error('删除失败：${response.message}');
      }
      
    } catch (e) {
      developer.log('💥 删除好友异常: $e');
      ToastUtil.error('删除好友失败，请重试');
    } finally {
      isDeletingFriend.value = false;
    }
  }
}

// 好友申请状态枚举
enum FriendRequestStatus {
  pending,   // 待处理
  accepted,  // 已通过
  rejected,  // 已拒绝
  expired,   // 已过期
}

// 好友申请模型
class FriendRequest {
  final String id;
  final String name;
  final String avatarUrl;
  final int level;           // 等级
  final String gender;       // 性别 (male/female)
  final String city;         // 城市
  final int age;            // 年龄
  final String signature;    // 个性签名
  final DateTime requestTime;
  final DateTime expireTime; // 失效时间
  FriendRequestStatus status; // 申请状态
  
  FriendRequest({
    required this.id,
    required this.name,
    required this.avatarUrl,
    required this.level,
    required this.gender,
    required this.city,
    required this.age,
    required this.signature,
    required this.requestTime,
    required this.expireTime,
    this.status = FriendRequestStatus.pending,
  });
  
  // 检查是否已过期
  bool get isExpired => DateTime.now().isAfter(expireTime);
  
  // 获取剩余时间
  Duration get remainingTime {
    final now = DateTime.now();
    if (now.isAfter(expireTime)) {
      return Duration.zero;
    }
    return expireTime.difference(now);
  }
  
  // 格式化剩余时间显示
  String get remainingTimeText {
    final remaining = remainingTime;
    if (remaining == Duration.zero) {
      return "已过期";
    }
    
    final hours = remaining.inHours;
    final minutes = remaining.inMinutes % 60;
    
    if (hours > 0) {
      return "${hours}小时${minutes}分钟后过期";
    } else {
      return "${minutes}分钟后过期";
    }
  }
}
